import uuid

from django.db import models
from django.utils import timezone

from apps.ProjectsManagement.models import Project


class ProjectHistory(models.Model):
    """项目历史记录表 - 分支结构"""

    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="记录ID", max_length=255)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='histories', verbose_name="关联项目")
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL,
                               related_name='children', verbose_name="父节点")
    branch_name = models.CharField(max_length=100, default="主分支", verbose_name="分支名称")

    # 快照数据
    project_snapshot = models.JSONField(verbose_name="项目快照")
    canvas_snapshot = models.JSONField(verbose_name="画布快照", default=list)
    element_snapshot = models.JSONField(verbose_name="元素快照", default=list)
    layer_snapshot = models.JSONField(verbose_name="图层快照", default=list)

    # 状态标记
    is_current = models.BooleanField(default=False, db_index=True, verbose_name="当前显示版本")
    is_checkpoint = models.BooleanField(default=False, verbose_name="是否为重要节点")
    checkpoint_desc = models.CharField(max_length=200, blank=True, null=True, verbose_name="节点描述")

    created_at = models.DateTimeField(default=timezone.now, db_index=True, verbose_name="操作时间")


    class Meta:
        db_table = 'project_history'
        verbose_name = '项目历史记录'
        verbose_name_plural = '项目历史记录'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['project', 'created_at']),
            models.Index(fields=['parent', 'branch_name'])
        ]
